package com.funsport.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.funsport.entity.Permission;
import com.funsport.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限服务
 */
@Service
public class PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    /**
     * 获取所有权限（树形结构）
     */
    public List<Permission> getTreeList() {
        // 获取所有权限
        List<Permission> allPermissions = permissionMapper.selectList(
            new QueryWrapper<Permission>().orderByAsc("sort_order")
        );
        
        // 构建树形结构
        return buildTree(allPermissions, null);
    }
    
    /**
     * 获取菜单权限（树形结构）
     */
    public List<Permission> getMenuTree() {
        List<Permission> menuPermissions = permissionMapper.selectMenuPermissions();
        return buildTree(menuPermissions, null);
    }
    
    /**
     * 根据ID获取权限
     */
    public Permission getById(Long id) {
        return permissionMapper.selectById(id);
    }
    
    /**
     * 创建权限
     */
    public Permission create(Permission permission) {
        permissionMapper.insert(permission);
        return permission;
    }
    
    /**
     * 更新权限
     */
    public Permission update(Permission permission) {
        permissionMapper.updateById(permission);
        return permission;
    }
    
    /**
     * 删除权限
     */
    public void delete(Long id) {
        permissionMapper.deleteById(id);
    }
    
    /**
     * 根据角色ID获取权限列表
     */
    public List<Permission> getByRoleId(Long roleId) {
        return permissionMapper.selectByRoleId(roleId);
    }
    
    /**
     * 根据用户ID获取权限列表
     */
    public List<Permission> getByUserId(Long userId) {
        return permissionMapper.selectByUserId(userId);
    }
    
    /**
     * 根据用户ID获取菜单权限（树形结构）
     */
    public List<Permission> getMenuTreeByUserId(Long userId) {
        List<Permission> userPermissions = permissionMapper.selectByUserId(userId);
        
        // 过滤出菜单权限
        List<Permission> menuPermissions = userPermissions.stream()
            .filter(p -> "menu".equals(p.getType()))
            .collect(Collectors.toList());
        
        return buildTree(menuPermissions, null);
    }
    
    /**
     * 构建权限树
     */
    private List<Permission> buildTree(List<Permission> permissions, Long parentId) {
        List<Permission> tree = new ArrayList<>();
        
        for (Permission permission : permissions) {
            if ((parentId == null && permission.getParentId() == null) ||
                (parentId != null && parentId.equals(permission.getParentId()))) {
                
                // 递归构建子树
                List<Permission> children = buildTree(permissions, permission.getId());
                if (!children.isEmpty()) {
                    permission.setChildren(children);
                }
                
                tree.add(permission);
            }
        }
        
        return tree;
    }
    
    /**
     * 根据用户ID获取权限编码列表
     */
    public List<String> getPermissionCodesByUserId(Long userId) {
        List<Permission> permissions = permissionMapper.selectByUserId(userId);
        return permissions.stream()
            .map(Permission::getCode)
            .collect(Collectors.toList());
    }
}

